package cn.com.hhrcw.web;

import cn.com.hhrcw.conferenceRoom.entity.ConferenceRoom;
import cn.com.hhrcw.conferenceRoom.mapstruct.ConferenceRoomConvert;
import cn.com.hhrcw.conferenceRoom.service.IConferenceRoomService;
import cn.com.hhrcw.entity.OpInterviewContact;
import cn.com.hhrcw.entity.OpInterviewHistory;
import cn.com.hhrcw.entity.PiInfo;
import cn.com.hhrcw.mapstruct.AdminOpInterviewHistoryConvert;
import cn.com.hhrcw.params.OpInterviewHistoryParams;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.sms.service.ISysSmsTemplateService;
import cn.com.hhrcw.utils.EmailSendUtil;
import cn.com.hhrcw.utils.EmailUtil;
import cn.com.hhrcw.utils.NewsUtil;
import cn.com.hhrcw.utils.huawei.CreateMeetingParam;
import cn.com.hhrcw.vo.OpInterviewHistoryVO;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;

/**
 * 职位-面试
 *
 * @author jiangdong
 * @since 2020-10-29
 */
@RestController
@Slf4j
@RequestMapping("/admin/opInterviewHistory")
@Api(tags = "职位-面试")
@Validated
public class AdminOpInterviewHistoryController extends JeecgController<OpInterviewHistory, IOpInterviewHistoryService> {

    @Autowired
    private IOpInterviewHistoryService opnterviewHistoryService;

    @Autowired
    private AdminOpInterviewHistoryConvert opInterviewHistoryConvert;
    @Autowired
    private EmailSendUtil emailSendUtil;
    @Autowired
    private NewsUtil newsUtil;

    @Autowired
    private IOpInterviewContactService contactService;

    @Autowired
    EmailUtil emailUtil;

    @Autowired
    private ISysSmsTemplateService service;

    @Autowired
    private IPiInfoService piInfoService;

    @Autowired
    IOpDeliveryHistoryService deliveryHistoryService;

    @Autowired
    private IOpInterviewHistoryService interviewHistoryService;

    @Autowired
    private ISysSmsTemplateService templateService;

    @Autowired
    private HuaWeiRoomService huaWeiRoomService;
    @Autowired
    private IConferenceRoomService conferenceRoomService;
    @Autowired
    private ConferenceRoomConvert conferenceRoomConvert;
    /**
     * 分页列表查询
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/listInterView")
    @AutoLog(value = "面试邀请列表",logType = 2,ty = "visit")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<Page<OpInterviewHistoryVO>> list(OpInterviewHistoryParams params, HttpServletRequest request) {
        QueryWrapper<OpInterviewHistory> queryWrapper = QueryGenerator.initQueryWrapper(opInterviewHistoryConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        IPage<OpInterviewHistory> page = opnterviewHistoryService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<OpInterviewHistory, OpInterviewHistoryVO> fun = opInterviewHistory -> opInterviewHistoryConvert.toVO(opInterviewHistory);

        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 根据id查询面试信息
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryByIdInterView")
    @AutoLog(value = "面试邀请查询",logType = 2,ty = "visit")
    @ApiOperation(value = "面试邀请查询", notes = "根据id查询")
    public Result<OpInterviewHistoryVO> queryById(String id) {
        OpInterviewHistory opInterviewHistory = opnterviewHistoryService
                .lambdaQuery()
                .eq(OpInterviewHistory::getId, id)
                .eq(OpInterviewHistory::getDelFlag, false)
                .one();
        if (opInterviewHistory == null) {
            throw new JeecgBootException("数据不存在");
        }
        OpInterviewHistoryVO opInterviewHistoryVO = opInterviewHistoryConvert.toVO(opInterviewHistory);
        if (StrUtil.isNotBlank(opInterviewHistoryVO.getRoomId())) {
            ConferenceRoom conferenceRoom = conferenceRoomService.getById(opInterviewHistoryVO.getRoomId());
            opInterviewHistoryVO.setConferenceRoomVO(conferenceRoomConvert.toVO(conferenceRoom));
            opInterviewHistoryVO.setR1(conferenceRoom.getHostUrl());
        }
        return Result.ok(opInterviewHistoryVO);
    }

    /**
     * /admin/opInterviewHistory/addInterviewData
     * 简历库-候选人-面试-视频面试（面试-非视频面试）
     *
     * @param params
     * @return
     */
    @PostMapping(value = "/addInterviewData")
    @AutoLog(value = "面试邀请添加",logType = 2,ty = "insert")
    @ApiOperation(value = "添加", notes = "添加")
    public Result<?> add(@RequestBody @Valid OpInterviewHistoryParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        OpInterviewHistory opInterviewHistory = opInterviewHistoryConvert.toEntity(params);

        Integer type = params.getType();
        if(type == 1){
            Date time = params.getTime();
            Date interviewEndTime = params.getInterviewEndTime();
            long between = DateUtil.between(interviewEndTime, time, DateUnit.MINUTE);
//            if(between > 1440){
//                throw new JeecgBootException("面试周期时间太长了");
//            }
            int a = 15;
            if(between < a){
                throw new JeecgBootException("面试周期最少15分钟");
            }
        }

        opInterviewHistory.setCreateBy(sysUser.getId());
        opInterviewHistory.setCreateTime(DateUtil.date());
        opInterviewHistory.setDelFlag(false);
        opInterviewHistory.setId(UUID.randomUUID().toString().substring(0, 32));
        boolean saved = opnterviewHistoryService.save(opInterviewHistory);
        if (saved) {
            String peopleIds = params.getPeopleIds();
            String userId = opInterviewHistory.getUserId();
            String viewId = opInterviewHistory.getId();
            String resumeId = opInterviewHistory.getResumeId();
            String jobId = opInterviewHistory.getJobId();

            if (StrUtil.isNotBlank(peopleIds)){
                String b = ",";
                if (peopleIds.contains(b)) {
                    String[] peopleId = peopleIds.split(",");
                    for (String p : peopleId) {
                        OpInterviewContact contact = new OpInterviewContact();
                        contact.setDelFlag(false);
                        contact.setCreateBy(sysUser.getId());
                        contact.setCreateTime(new Date());
                        contact.setId(UUID.randomUUID().toString().substring(0, 32));
                        contact.setJobId(jobId);
                        contact.setViewId(viewId);
                        contact.setUserId(userId);
                        contact.setResumeId(resumeId);
                        contact.setContactId(p);
                        contactService.save(contact);
                    }
                } else {
                    OpInterviewContact contact = new OpInterviewContact();
                    contact.setDelFlag(false);
                    contact.setCreateBy(sysUser.getId());
                    contact.setCreateTime(new Date());
                    contact.setId(UUID.randomUUID().toString().substring(0, 32));
                    contact.setJobId(jobId);
                    contact.setViewId(viewId);
                    contact.setUserId(userId);
                    contact.setResumeId(resumeId);
                    contact.setContactId(peopleIds);
                    contactService.save(contact);
                }
            }

            //todo 根据peopleIds生成面试官信息

            Map<String, String> emailMap = emailUtil.creatEmail(userId, sysUser.getId(), 0, 1, opInterviewHistory.getId(), "1");
            String title = emailMap.get("tittle");
            String content = emailMap.get("content");
            PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, userId).one();
            if (params.getEmailFlag() != null && params.getEmailFlag()) {
                //邮件
                Map<String, String> emailMap1 = emailSendUtil.creatEmail(userId, sysUser.getId(), 0, 1, opInterviewHistory.getId(), "1");
                String title1= emailMap1.get("tittle");
                String content1 = emailMap1.get("content");
                service.sendEmail(content1, title1,(File) null ,piInfo.getEmail());
            }
            if (params.getCcFlag() != null && params.getCcFlag()) {
                //todo 抄送同事
            }
            //手机短信
            templateService.sendSms(new String[]{piInfo.getPhone()}, "【" + title + "】" + content);
            newsUtil.creatNews(params.getUserId(), sysUser.getId(), 0, 1, opInterviewHistory.getId(), "1");
        }

        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
     * 修改面试信息
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/editInterView")
    @AutoLog(value = "面试邀请编辑",logType = 2,ty = "update")
    @ApiOperation(value = "编辑", notes = "编辑")
    public Result<?> edit(@RequestBody @Valid OpInterviewHistoryParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        OpInterviewHistory opInterviewHistory = opInterviewHistoryConvert.toEntity(params);


        OpInterviewHistory byId = opnterviewHistoryService.getById(params.getId());
        if(null != params.getTime()){
            if(DateUtil.compare(new Date(),params.getTime()) >= 0){
                return Result.error("选择的面试时间已过，无法进行面试");
            }
        }

        if(null != params.getTime() && byId.getType() == 1){

            if(StringUtils.isNotBlank(byId.getR2())){
                return Result.error("会议时间已不可修改");
            }

            // 修改面试房间预约时间
            Date time = params.getTime();
            Date interviewEndTime = params.getInterviewEndTime();
            long between = DateUtil.between(interviewEndTime, time, DateUnit.MINUTE);
            int c = 1440;
            if(between > c){
                throw new JeecgBootException("面试周期时间太长了");
            }
            int d = 15;
            if(between < d){
                throw new JeecgBootException("面试周期最少15分钟");
            }

        }
        opInterviewHistory.setUpdateBy(sysUser.getId());
        opInterviewHistory.setUpdateTime(DateUtil.date());

        boolean updated = opnterviewHistoryService.updateById(opInterviewHistory);

        if (params.getIsResult() != null && params.getIsResult()) {
            //消息内容类型 类型0投递1面试2录用3拒绝面试4接受面试5阅读6接受入职7拒绝入职8简历不合适通知
            if (params.getViewResult() != null) {
                Map<String, String> map = null;
                //面试结果  0通过 1没通过
                if (params.getViewResult() == 0) {
                    map = emailUtil.creatEmail(opInterviewHistory.getUserId(), sysUser.getId(), null, null, opInterviewHistory.getId(), "9");
                    newsUtil.creatNews(params.getUserId(), sysUser.getId(), 0, 1, opInterviewHistory.getId(), "9");
                } else {
                    map = emailUtil.creatEmail(opInterviewHistory.getUserId(), sysUser.getId(), null, null, opInterviewHistory.getId(), "10");
                    newsUtil.creatNews(params.getUserId(), sysUser.getId(), 0, 1, opInterviewHistory.getId(), "10");
                }
                PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, opInterviewHistory.getUserId()).one();
                String title = map.get("tittle");
                String content = map.get("content");
                //短信
                templateService.sendSms(new String[]{piInfo.getPhone()}, "【" + title + "】" + content);
                Map<String, String> map1 = null;
                //面试结果  0通过 1没通过
                if (params.getViewResult() == 0) {
                    map1 = emailSendUtil.creatEmail(opInterviewHistory.getUserId(), sysUser.getId(), null, null, opInterviewHistory.getId(), "9");
                } else {
                    map1 = emailSendUtil.creatEmail(opInterviewHistory.getUserId(), sysUser.getId(), null, null, opInterviewHistory.getId(), "10");
                }
                String title1 = map1.get("tittle");
                String content1 = map1.get("content");
                //邮件
                service.sendEmail(content1, title1,(File) null ,piInfo.getEmail());

            }
        }
        if (params.getTime() != null) {

            PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, opInterviewHistory.getUserId()).one();
            Map<String, String> map = emailUtil.creatEmail(opInterviewHistory.getUserId(), sysUser.getId(), null, null, opInterviewHistory.getId(), "11");
            newsUtil.creatNews(params.getUserId(), sysUser.getId(), 0, 1, opInterviewHistory.getId(), "11");
            //短信
            String title = map.get("tittle");
            String content = map.get("content");
            templateService.sendSms(new String[]{piInfo.getPhone()}, "【" + title + "】" + content);
            Map<String, String> map1 = emailSendUtil.creatEmail(opInterviewHistory.getUserId(), sysUser.getId(), null, null, opInterviewHistory.getId(), "11");
            String title1 = map1.get("tittle");
            String content1 = map1.get("content");
            //邮件
            service.sendEmail(content1, title1,(File)null, piInfo.getEmail());
        }
        return updated ? Result.ok() : Result.error("编辑失败");
    }


    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/deleteInterView")
    @AutoLog(value = "面试邀请删除",logType = 2,ty = "delete")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("opInterviewHistory:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<OpInterviewHistory> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(OpInterviewHistory::getId, id)
                .set(OpInterviewHistory::getDelFlag, true)
                .set(OpInterviewHistory::getUpdateBy, sysUser.getUsername())
                .set(OpInterviewHistory::getUpdateTime, DateUtil.date());

        boolean deleted = opnterviewHistoryService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeatInterView")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXlsInterView")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, OpInterviewHistoryParams params) {
        OpInterviewHistory opInterviewHistory = opInterviewHistoryConvert.toEntity(params);
        opInterviewHistory.setDelFlag(false);
        QueryWrapper<OpInterviewHistory> queryWrapper = QueryGenerator.initQueryWrapper(opInterviewHistory, request.getParameterMap());
        List<OpInterviewHistory> data = opnterviewHistoryService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("职位-面试", "职位-面试");
        String url = super.exportXls(exportParams, OpInterviewHistoryVO.class, opInterviewHistoryConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcelInterView")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OpInterviewHistory.class);
    }

}
